package com.ztgf.commodity.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.common.config.YmlConfig;
import com.ztgf.commodity.mapper.CommodityCategoryFilterRelationMapper;
import com.ztgf.commodity.models.dto.CommodityCategoryFilterRelationDTO;
import com.ztgf.commodity.models.dto.CommodityFilterAttributesDTO;
import com.ztgf.commodity.models.service.ICommodityCategoryFilterRelationService;
import com.ztgf.commodity.models.service.ICommodityFilterAttributesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.ztgf.common.utils.UtilConstants.ZERO;
import static com.ztgf.common.utils.UtilConstants.isNull;

/*
 * @author: chenyu.wang
 * @date: 2020-09-07
 * @description:
 */
@Slf4j
@DubboService
public class CommodityCategoryFilterRelationServiceImpl extends ServiceImpl<CommodityCategoryFilterRelationMapper, CommodityCategoryFilterRelationDTO> implements ICommodityCategoryFilterRelationService {


    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private ICommodityFilterAttributesService commodityFilterAttributesService;


    /*
     * @description:添加类目筛选属性表，只有0级筛选属性才能添加
     * @author: chenyu.wang
     * @date: 2020-09-07
     */
    @Override
    public void add(Long categoryId, String filterIds) {
        List<CommodityCategoryFilterRelationDTO> list = new ArrayList<>();
        String[] ids = filterIds.split(",");
        for (String id : ids) {
            CommodityFilterAttributesDTO attributesDTO = commodityFilterAttributesService.selectById(id);
            if (attributesDTO.getParentId() == ZERO) {
                CommodityCategoryFilterRelationDTO relationDTO = new CommodityCategoryFilterRelationDTO();
                relationDTO.setCategoryId(categoryId);
                relationDTO.setFilterAttributesId(Long.valueOf(id));
                relationDTO.setId(ymlConfig.getPkId());
                list.add(relationDTO);
            }
        }
        this.insertBatch(list);
    }

    /*
     * @description:根据类目id删除关联表
     * @author: chenyu.wang
     * @date: 2020-09-07
     */
    @Override
    public void deleteByCategoryId(Long categoryId) {
        Wrapper<CommodityCategoryFilterRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("category_id", categoryId);
        boolean delete = this.delete(wrapper);
        if (delete) {
            log.info("删除成功!");
        } else {
            log.info("删除失败!");
        }

    }
}
